package com.iphaeton.lms.course.scorm12.runtime.core;

import com.iphaeton.common.helper.UserSession;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.xml.sax.InputSource;

public class ScormCourseImportServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String sessionID = new String();
		String uploadDir = new String();
		String userDir = new String();
		String error = new String();
		try {
			SmartUpload myUpload = new SmartUpload();

			sessionID = request.getSession().getId();

			String theWebPath = getServletConfig().getServletContext()
					.getRealPath("/");

			myUpload.initialize(getServletConfig(), request, response);
			myUpload.upload();

			uploadDir = "\\SampleRTEFiles\\tempUploads\\" + sessionID;
			File theRTEUploadDir = new File(uploadDir);

			if (!(theRTEUploadDir.isDirectory())) {
				theRTEUploadDir.mkdirs();
			}

			int count2 = myUpload.save(uploadDir, 2);

			String courseTitle = myUpload.getRequest().getParameter(
					"coursename");
			String zipFile = myUpload.getRequest().getParameter("theZipFile");

			String controlType = myUpload.getRequest().getParameter(
					"controltype");
			String createrId = ((UserSession) request.getSession()
					.getAttribute("userSession")).getId();

			LMSPackageHandler myPackageHandler = new LMSPackageHandler();
			LMSPackageHandler.extract(zipFile, "imsmanifest.xml", uploadDir);

			String manifestFile = uploadDir + "\\" + "imsmanifest.xml";
			String newZip = zipFile.substring(zipFile.lastIndexOf("\\") + 1);
			zipFile = uploadDir + "\\" + newZip;

			LMSManifestHandler myManifestHandler = new LMSManifestHandler();

			InputSource fileToParse = setUpInputSource(manifestFile);
			myManifestHandler.setCourseName(courseTitle);
			myManifestHandler.setFileToParse(fileToParse);
			myManifestHandler.setControl(controlType);
			myManifestHandler.setCreater(createrId);

			boolean result = myManifestHandler.processManifest();

			String courseID = myManifestHandler.getCourseID();

			ZipFile archive = new ZipFile(zipFile);

			byte[] buffer = new byte[16384];

			for (Enumeration e = archive.entries(); e.hasMoreElements();) {
				int count;
				ZipEntry entry = (ZipEntry) e.nextElement();

				if (!entry.isDirectory()) {

					String filename = entry.getName();
					filename = filename.replace('/', File.separatorChar);
					filename = theWebPath + "CourseImports\\" + courseID + "\\"
							+ filename;
					File destFile = new File(filename);

					String parent = destFile.getParent();
					if (parent != null) {
						File parentFile = new File(parent);
						if (!(parentFile.exists())) {
							parentFile.mkdirs();
						}

					}

					InputStream in = archive.getInputStream(entry);

					OutputStream outStream = new FileOutputStream(filename);

					while ((count = in.read(buffer)) != -1)
						outStream.write(buffer, 0, count);

					in.close();
					outStream.close();
				}

			}

			String sequencingFileName = theWebPath + "CourseImports\\"
					+ courseID + "\\sequence.obj";
			File sequencingFile = new File(sequencingFileName);
			FileOutputStream ostream = new FileOutputStream(sequencingFile);
			ObjectOutputStream oos = new ObjectOutputStream(ostream);
			oos.writeObject(myManifestHandler.getOrgsCopy());
			oos.flush();
			oos.close();

			boolean wasdeleted = false;
			File[] uploadFiles = theRTEUploadDir.listFiles();
			for (int i = 0; i < uploadFiles.length; ++i)
				uploadFiles[i].deleteOnExit();

			theRTEUploadDir.deleteOnExit();

			response.setContentType("text/html");
			response.sendRedirect(request.getContextPath()
					+ "/pages/course/confirmImport.jsp");
		} catch (Exception e) {
			error = e.toString();
		}
	}

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		doPost(arg0, arg1);
	}

	private InputSource setUpInputSource(String fileName) {
		InputSource is = new InputSource();
		is = setupFileSource(fileName);
		return is;
	}

	private InputSource setupFileSource(String filename) {
		File xmlFile;
		try {
			xmlFile = new File(filename);
			if (xmlFile.isFile()) {
				FileReader fr = new FileReader(xmlFile);
				InputSource is = new InputSource(fr);
				return is;
			}

		} catch (NullPointerException npe) {
			System.out.println("Null pointer exception" + npe);
		} catch (SecurityException se) {
			System.out.println("Security Exception" + se);
		} catch (FileNotFoundException fnfe) {
			System.out.println("File Not Found Exception" + fnfe);
		}
		label119: return new InputSource();
	}
}